/*
 * Chat.java
 *
 * Created on 15 2007 22:37
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package server.utils;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.transaction.UserTransaction;

/**
 *
 * @author alexog
 */
public class Chat {
    /** Creates a new instance of Chat */
    public Chat() {
    }
    
    public static void write(String message) {
        try {
            TopicConnection connection = ServiceLocator.getInstance().getTopicConnectionFactory("java:comp/env/jms/connectionFactory").createTopicConnection();
            connection.start();
            TopicSession session = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("java:comp/env/jms/chatTopic");
            TextMessage msg = session.createTextMessage();
            msg.setText(message);
            TopicPublisher publisher = session.createPublisher(topic);
            publisher.publish(msg);
            // cleanup
            publisher.close();
            session.close();
        } catch (JMSException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
        
    }
    
    public static String read(){
        String message = "";
        TopicConnection connection;
        try {
            connection = ServiceLocator.getInstance().getTopicConnectionFactory("jms/connectionFactory").createTopicConnection();
            connection.start();
            TopicSession session = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic("java:comp/env/jms/chatTopic");
            TopicSubscriber subscriber = session.createSubscriber(topic);
            TextMessage msg = (TextMessage)subscriber.receive();
            message = msg.getText();
            subscriber.close();
            session.close();
        } catch (JMSException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch( Exception ex ) {
            ex.printStackTrace();
        } finally {
        }
        return(message);
    }
}
